<?php
namespace Home\Model;
use \Think\Db;
use Think\Model;

class B2cOrdersModel extends Model{



    /**
     * 订单列表
     * pay_status 支付状态
     *  0 => app::get('b2c')->_('未支付'),
    1 => app::get('b2c')->_('已支付'),
     *
     * ship_status 发货状态
     * 0 => app::get('b2c')->_('未发货'),
    1 => app::get('b2c')->_('已发货'),
     *
     * received_status 收货状态
     * 0 => app::get('b2c')->_('未收货'),
     * 1 => app::get('b2c')->_('已收货'),
     *
     * refund_status 退款状态
     * 0-未申请退款，1-申请退款，2-退款完成'
     *
     * refund_goods_status 退货退款状态
     * 0未申请退货，1-申请退货退款，2退货退款完成'
     *
     * comment_status 评价
     * 0-不能评价，1-未评价，2已经评价',
     *
     * 订单状态 status
     *
     * 'active' => app::get('b2c')->_('活动订单'),
     * 'dead' => app::get('b2c')->_('已作废'),
     * 'finish' => app::get('b2c')->_('已完成'),
     *
     * is_delivery 是否需要发货
     * Y => app::get('b2c')->_('是否需要发货'),
     * N => app::get('b2c')->_('是否需要发货'),
     *
     * pre_delivery_time 预约自提时间
     *
     * pickedup_bn   自提单号
     *
     * mark_text  操作员订单备注
     *
     *
     * shipping_id  配送方式（table:dlytype）
     *
     *
     */
    public function orderList($view,$member_id = 0,$local_id = 0,$p = 0){
        $sub = array(
            0=>array('o.pay_status'=>'1','o.ship_status'=>'0','o.status'=>'active','o.local_id'=> $local_id,'o.member_id'=>$member_id),// 待发货
            1=>array('o.pay_status'=>'1','o.ship_status'=>'1','o.received_status'=>'0','o.status'=>'active','o.local_id'=> $local_id,'o.member_id'=>$member_id),// 已发货
            2=>array('o.pay_status'=>'1','o.ship_status'=>'1','o.received_status'=>'1','o.status'=>'active','o.local_id'=> $local_id,'o.member_id'=>$member_id), //已收货  部分发货，不能确认收货 提示货没发完，收货定时任务，判断 发货状态是 1
            3=>array('o.pay_status'=>'0','o.status'=>'active','o.local_id'=> $local_id,'o.member_id'=>$member_id),//待支付
            4=>array('o.status'=>'dead','o.local_id'=> $local_id,'o.member_id'=>$member_id),//已经作废【未支付订单超时】，定时返回库存
            5=>array('o.status'=>'finish','o.local_id'=> $local_id,'o.member_id'=>$member_id),//已完成
            6=>array('o.status'=>['NEQ','delete'],'o.local_id'=> $local_id,'o.member_id'=>$member_id),//查询全部非删除的订单
            7=>array(['o.refund_ago_goods_status'=>'1','o.refund_ago_money_status'=>'1','o.refund_front_status'=>'1','_logic'=>'or'],'o.local_id'=>$local_id,'o.member_id'=>$member_id),//退款中
            8=>array('o.comment_status'=>'1','o.status'=>'active','o.local_id'=>$local_id,'o.member_id'=>$member_id),//未评论
            9=>array('o.comment_status'=>'2','o.status'=>'active','o.local_id'=>$local_id,'o.member_id'=>$member_id),//以评论
            10=>array('o.pay_status'=>'1','o.ship_status'=>'1','o.received_status'=>'0','o.status'=>'active','o.local_id'=> $local_id,'o.member_id'=>$member_id),// 待收货
            11=>array('o.status'=>['in','active,dead'],'o.local_id'=> $local_id,'o.member_id'=>$member_id),//查询全部正常和失效的订单
        );

        if($member_id == 0){
            unset($sub[$view]['o.member_id']);
        }
        if($local_id == 0){
            unset($sub[$view]['o.local_id']);
        }

        $where[] = $sub[$view];
        if($p){
            $orderList =  $this->alias('o')
                ->field("o.*,d.logi_name,d.logi_no,s.tel")
                //物流信息
                ->join("left join ".C('DB_PREFIX')."b2c_delivery d on o.order_id = d.order_id")
                ->join("left join ".C('DB_PREFIX')."webpos_local_store s on s.local_id = o.local_id")
                ->where($where)
                ->page($p.",5")->order('o.createtime desc')->select();

            $count   = M('b2c_orders o')->where($where)->count();// 查询满足要求的总记录数

            $Page       = new \Think\Page($count,5);// 实例化分页类 传入总记录数和每页显示的记录数
            $show       = $Page->show();// 分页显示输出
            $payList['page'] = $show;
        }else{
            $orderList =  $this->alias('o') ->field("o.*,d.logi_name,d.logi_no,s.tel")
                //物流信息
                ->join("left join ".C('DB_PREFIX')."b2c_delivery d on o.order_id = d.order_id")
                ->join("left join ".C('DB_PREFIX')."webpos_local_store s on s.local_id = o.local_id")
                ->where($where)
                ->order('o.createtime desc')->select();
        }
        //dump($orderList);
        //echo $this->_sql();die;
        $table1 = "(SELECT  a.goods_id,b.* FROM sdb_b2c_goods a LEFT JOIN sdb_image_image b ON a.image_default_id = b.image_id) ";
        $table2 = "(SELECT re_m.status AS rem_status,re_m.type,re_g.order_id,re_g.item_id FROM sdb_b2c_refund_money re_m".
            " LEFT JOIN sdb_b2c_refund_money_goods re_g  ON ".
            "re_g.refund_money_id = re_m.id WHERE re_m.`status` not in ('0','6','7') GROUP BY re_g.`item_id`)";
        //dump($orderList);die;
        foreach ($orderList as $k=>$item){
            $orderList[$k]['time'] = date('Y-m-d H:i:s',$item['createtime']);
            $item_order = M('b2c_order_items')->alias('o')
                ->field("o.*,re.rem_status,IF(re.type, re.type, - 1) AS re_type,g.url,g.l_url,g.m_url,g.s_url")
                ->join('left join '.$table1.' g on g.goods_id=o.goods_id')
                ->join('left join '.$table2.' re on re.order_id=o.order_id and re.item_id=o.item_id')
                ->where(['o.order_id' => $item['order_id']])
                ->select();
            //echo M('b2c_order_items')->_sql().'<br/>';
            if($item_order){
                $orderList[$k]['item_order'] = $item_order;
            }
            //$orderList[$k]['is_zt'] = $item['is_zt'] == 1 ? '<span style="color: #ff2e49">自提订单</span>':'普通订单';
            //订单备注最新信息
            if(!empty($item['mark_text'])){
                $mark =unserialize( $item['mark_text']);
                $markContent = end($mark);
                $orderList[$k]['mark'] =  $markContent['mark_text'];
            }
            //$orderList[$k]['action'] = $this->actionButton($item['order_id'],$view);
        }
        $payList['list'] = $orderList;
        //dump($payList);
        if(!empty($payList)){
            return $payList;
        }else{
            return array('msg'=>'暂无订单','status'=>2);
        }

    }

    /**
     * 查询会员订单数量
     */
    public function countList($view,$member_id = 0,$local_id = 0){
        $sub = array(
            0=>array('pay_status'=>'1','ship_status'=>'0','status'=>'active','local_id'=>$local_id,'member_id'=>$member_id),// 待发货
            1=>array('pay_status'=>'1','ship_status'=>'1','received_status'=>'0','status'=>'active','local_id'=>$local_id,'member_id'=>$member_id),// 已发货
            2=>array('pay_status'=>'1','ship_status'=>'1','received_status'=>'1','status'=>'active','local_id'=>$local_id,'member_id'=>$member_id), //已收货  部分发货，不能确认收货 提示货没发完，收货定时任务，判断 发货状态是 1
            3=>array('pay_status'=>'0','status'=>'active','local_id'=>$local_id,'member_id'=>$member_id),//待支付
            4=>array('status'=>'dead','local_id'=>$local_id,'member_id'=>$member_id),//已经作废【未支付订单超时】，定时返回库存
            5=>array('status'=>'finish','local_id'=>$local_id,'member_id'=>$member_id),//已完成
            //6=>array('pay_status'=>'1','is_zt'=>1,'status'=>'active','local_id'=>$local_id),//门店自提  [完成按钮]  状态 finish 库存操作
            6=>array('status'=>['NEQ','delete'],'local_id'=>$local_id,'member_id'=>$member_id),//查询全部订单
            7=>array(['refund_ago_goods_status'=>'1','refund_ago_money_status'=>'1','refund_front_status'=>'1','_logic'=>'or'],'refund_status'=>'0','local_id'=>$local_id,'member_id'=>$member_id),//退款中
            8=>array('comment_status'=>'1','status'=>'active','local_id'=>$local_id,'member_id'=>$member_id),//未评论
            9=>array('comment_status'=>'2','status'=>'active','local_id'=>$local_id,'member_id'=>$member_id),//以评论
            10=>array('pay_status'=>'1','ship_status'=>'1','received_status'=>'0','status'=>'active','local_id'=> $local_id,'member_id'=>$member_id),// 待收货
        );
        if($member_id == 0){
            unset($sub[$view]['member_id']);
        }
        if($local_id == 0){
            unset($sub[$view]['local_id']);
        }
        $where[] = $sub[$view];
        $count = $this->where($where)->count();
        //echo M()->_sql();die;
        return $count;
    }

    /**
     * @param string $order_id
     * 订单详细
     */
    public function orderDetail($order_id){

        $table1 = "(SELECT m.*,mg.item_id,mg.num FROM `sdb_b2c_refund_money` m LEFT JOIN `sdb_b2c_refund_money_goods` mg ".
            "ON m.order_id = mg.order_id AND m.id = mg.refund_money_id AND `status` not in ('0', '6','7') WHERE m.`order_id`='{$order_id}' GROUP BY mg.`item_id`)";
        $table2 = "(SELECT a.goods_id,b.* FROM sdb_b2c_goods a LEFT JOIN sdb_image_image b ON a.image_default_id = b.image_id) ";

        $orderGoods =  M('b2c_order_items i')
            ->field("i.*,t.num,IF(t.status,t.status,-1) AS t_status,t.type as t_type ,ima.url,ima.l_url,ima.m_url,ima.s_url")
            ->join("left join {$table1} t on t.item_id = i.item_id")
            ->join("left join {$table2} ima on ima.goods_id=i.goods_id")
            ->where(['i.order_id'=>$order_id])
            ->select();
        //echo M('b2c_order_items i')->_sql();
        return $orderGoods;

    }


    /**
     * @param string $order
     * @param $view
     * @return mixed
     *
     */
    public function  actionButton($order='',$view){

        $url = U("orders/orderDetail/",['id'=>$order]);
        $urlMark = U("orders/orderMark/",['id'=>$order]);
        $urlDeli = U("orders/orderDelivery/",['id'=>$order]);
        $finishBut = "isSure($order)";
        $ztBut = "isZtSure($order)";
        $action  = array(
            /*0=>"<a href='#' >发货</a><a href='".$url."'>查看订单</a><a href='#'>订单备注</a>",*/
            0=>"<div class='edit-list'><ul class='order-edit'>
	                <li><a href='#' class='suggest' data-id='$urlDeli' >发货</a></li>
	                <li class='cur'><a href='".$url."'>查看订单</a></li>
	                <li><a href='".$urlMark."'>订单备注</a></li>
                </ul>
                </div>",
            1=>"<div class='edit-list'><ul class='order-edit'>
                      <li><a href='".$url."' >查看订单</a></li>
                        <li><a href='#' >退货</a></li>                          
                        <li><a href='".$urlMark."'>订单备注</a></li>
                      </ul>
                </div>
            ",
            2=>"<div class='edit-list'><ul class='order-edit'>
                      <li><a href='".$url."' >查看订单</a></li>
                        <li><a href='#' >退货</a></li>
                         <li class='cur'><a href='javascript:void(0);' onclick='".$finishBut."'>完成</a></li>
                         <li><a href='".$urlMark."'>订单备注</a></li>
                      </ul>
                </div>",
            3=>"<div class='edit-list'><ul class='order-edit'>
                      <li  class='cur'><a href='".$url."' >查看订单</a></li>
                      <li><a href='".$urlMark."'>订单备注</a></li>
                      </ul>
                </div>",
            4=>"<div class='edit-list'><ul class='order-edit'>
                      <li  class='cur'><a href='".$url."' >查看订单</a></li>
                    </ul>
                </div>",
            5=>"<div class='edit-list'><ul class='order-edit'>
                      <li  class='cur'><a href='".$url."' >查看订单</a></li>
                       <li><a href='#'>订单备注</a></li>
                      </ul>
                </div>",
         /*   6=>"<div class='edit-list'><ul class='order-edit'>
                      <li  class='cur'><a href='".$url."' >查看订单</a></li>
                       <li class='cur'><a href='javascript:void(0);' onclick='".$ztBut."'>完成</a></li>

                      </ul>
                </div>",*/
            6=>"<div class='edit-list'><ul class='order-edit'>
                      <li  class='cur'><a href='".$url."' >查看订单</a></li></ul></div>",
        );

        return $action[$view];

    }

    public function saveMark($order_id,$text){



        if(empty($text)){
            return array('msg'=>'内容不能为空','status'=>0);
        }
        $arr = array('0'=>[
             'mark_text'=>$text,
               'add_time'=>time(),
               'op_name'=>session('userInfo.username'),
        ]

        );

        $recontent = "<tr><td>".$arr[0]['op_name']."</td><td>".$arr[0]['mark_text']."</td><td>".date('Y-m-d H:i:s',$arr[0]['add_time'])."</td></tr>";



        $oldArr = $this->markList($order_id);

        if(!empty($oldArr)){
            $newArr = array_merge($oldArr,$arr);
            $val = serialize($newArr);
        }else{
            $val = serialize($arr);
        }


        $result = M('b2c_orders')->where(['order_id'=>$order_id,'local_id'=>session('userInfo.local_id')])->save(['mark_text'=>$val]);

        if($result){
            return array('msg'=>'保存成功','status'=>1,'content'=>$recontent);
        }else{
            return array('msg'=>'保存失败','status'=>0);
        }

    }

    /**
     * 备注内容list
     */
    public function markList($order_id=''){

        $mark = M('b2c_orders')->where(['order_id'=>$order_id,'local_id'=>session('userInfo.local_id')])->field('mark_text')->find();

        if(!empty($mark)){
            $markArr = unserialize($mark['mark_text']);
            foreach ($markArr as $k=>$item){
                $markArr[$k]['add_time'] = date('Y-m-d H:i:s',$item['add_time']);
            }

        }

        return $markArr;
    }

    /**
     * 订单日志
     */
    public function ordreLog($order_id=''){

        $Log = M('b2c_order_log olog')
            ->join("left join ".C('DB_PREFIX')."b2c_orders o on o.order_id = olog.rel_id")
            ->where(['olog.rel_id'=>$order_id,'o.local_id'=>session('userInfo.local_id')])->select();

        if(empty($Log)){
            return array('msg'=>'参数错误','status'=>0);
        }
        foreach ($Log as $k=>$item){
            $Log[$k]['time'] =  date('Y-m-d H:i:s',$item['alttime']);

            if($item['result']=='SUCCESS'){
                $Log[$k]['result'] = '成功' ;
            }else{
                $Log[$k]['result'] = '失败';
            }

            switch ($item['behavior']) {
                case 'creates':
                    $Log[$k]['behavior'] = "创建";
                    if ($arr_log_text = unserialize($item['log_text']))
                    {
                        $item['log_text'] = '';
                        foreach ($arr_log_text as $arr_log)
                        {
                            $Log[$k]['log_text'] .= $arr_log['txt_key'];
                        }
                    }


                    break;
                case 'updates':
                    $Log[$k]['behavior'] = "修改";
                    if ($arr_log_text = unserialize($item['log_text']))
                    {
                        $Log[$k]['log_text'] = '';
                        foreach ($arr_log_text as $arr_log)
                        {
                            $Log[$k]['log_text'] .= $arr_log['txt_key'];
                        }
                    }
                    break;
                case 'payments':
                    $Log[$k]['behavior'] = "支付";
                    if ($arr_log_text = unserialize($item['log_text']))
                    {
                        $Log[$k]['log_text'] = '';
                        foreach ($arr_log_text as $arr_log)
                        {
                           // $Log[$k]['log_text'] .= $arr_log['txt_key'],$arr_log['data'][0],$arr_log['data'][1],$arr_log['data'][2];
                        }
                    }
                    break;
                case 'refunds':
                    $Log[$k]['behavior'] = "退款";
                    if ($arr_log_text = unserialize($item['log_text']))
                    {
                        $Log[$k]['log_text'] = '';
                        foreach ($arr_log_text as $arr_log)
                        {
                            $Log[$k]['log_text'] .= $arr_log['txt_key'];
                        }
                    }
                    break;
                case 'delivery':
                    $Log[$k]['behavior'] = "发货";
                    if ($arr_log_text = unserialize($item['log_text']))
                    {
                        $Log[$k]['log_text'] = '';
                        foreach ($arr_log_text as $arr_log)
                        {
                          //  $Log[$k]['log_text'] .= $arr_log['txt_key'],$arr_log['data'][0],$arr_log['data'][1],$arr_log['data'][2],$arr_log['data'][3],$arr_log_text['data'][4],$arr_log['data'][5];
                        }
                    }
                    break;
                case 'reship':
                    $Log[$k]['behavior'] = "退货";
                    if ($arr_log_text = unserialize($item['log_text']))
                    {
                        $Log[$k]['log_text'] = '';
                        foreach ($arr_log_text as $arr_log)
                        {
                           // $Log[$k]['log_text'] .= $arr_log['txt_key'],$arr_log['data'][0],$arr_log['data'][1],$arr_log['data'][2],$arr_log['data'][3],$arr_log_text['data'][4],$arr_log['data'][5];
                        }
                    }
                    break;
                case 'finish':
                    $Log[$k]['behavior'] = "完成";
                    if ($arr_log_text = unserialize($item['log_text']))
                    {
                        $Log[$k]['log_text'] = '';
                        foreach ($arr_log_text as $arr_log)
                        {
                            $Log[$k]['log_text'] .= $arr_log['txt_key'];
                        }
                    }
                    break;
                case 'cancel':
                    if ($arr_log_text = unserialize($item['log_text']))
                    {
                        $Log[$k]['log_text']= '';
                        foreach ($arr_log_text as $arr_log)
                        {
                            $Log[$k]['log_text'] .= $arr_log['txt_key'];
                        }
                    }
                    $Log[$k]['behavior'] = "作废";
                    break;
                case 'receive':
                    $Log[$k]['behavior'] = "确认收货";
                    break;
                case 'member_refund':
                    $Log[$k]['behavior'] = "会员退款";
                    break;
                case 'member_refund_goods':
                    $Log[$k]['behavior'] = "会员退货退款";
                    break;
                default:
                    break;
            }
        }

        return $Log;

    }

    /**
     * 发货订单操作日志
     */
    public function addOrderLog($delivery_id,$orderGoods){

        $delivery_log = array(
            'rel_id'=>$delivery_id['order_id'],
            'op_id'=>session('userInfo.local_id'),
            'op_name'=>session('userInfo.username'),
            'alttime'=>time(),
            'bill_type'=>'order',
            'behavior'=>'delivery',
            'result'=>'SUCCESS',


        );
        //是否是部分发货


        $content ='';
        foreach ($orderGoods['product'] as $k=>$item){
            if($item['nums']- $delivery_id['send'][$item['item_id']]>0){
               $content .=  "<br>部分发货商品：".$item['name']."数量：".$delivery_id['send'][$item['item_id']];
            }else{
                $content .=  "<br>发货商品：".$item['name']."数量：".$delivery_id['send'][$item['item_id']];
            }

        }

       // item_id

        $dlytype =  M('b2c_dlytype')->where(['dt_id'=>$delivery_id['delivery']])->field('dt_name')->find();

        $dlycorp =  M('b2c_dlycorp')->where(['corp_id'=>$delivery_id['logi_id']])->field('name')->find();
        if(!empty($delivery_id['logi_no'])){
            $logi_no =  ",物流单号:".$delivery_id['logi_no'];
        }
        $delivery_log['log_text'] = "发货完成，配送方式:".$dlytype['dt_name'].",物流公司：".$dlycorp['name'].$logi_no."，物流费用:".$delivery_id['money'].$content;


        $result = M('b2c_order_log')->data($delivery_log)->add();
        if($result){
            return array('msg'=>'添加发货日志成功','status'=>1);
        }else{
            return array('msg'=>'添加发货日志失败','status'=>0);
        }

    }



    /**
     * 发货详情
     */

    public function ordreDe($order_id =''){

        $orderGoods = $this->orderDetail($order_id);

        //查找配送方式
        $dlytype =  M('b2c_dlytype')->field('dt_id,dt_name')->select();
        $orderGoods['dlytype'] = $dlytype;
        //查找物流公司
        $dlycorp =  M('b2c_dlycorp')->field('corp_id,name')->select();
        $orderGoods['dlycorp'] = $dlycorp;

        //查询配送方式对应的 物流公司

        $dly =  M('b2c_dlytype dt')
            ->join("left join ".C('DB_PREFIX')."b2c_dlycorp dc on dt.corp_id = dc.corp_id")
            ->where(['dt.dt_id'=>$orderGoods['detail']['shipping_id']])
            ->field("dc.corp_id")
            ->find();

        $orderGoods['se_corp_id'] = $dly['corp_id'];
        $orderGoods['dlycorp'] = $dlycorp;


        return $orderGoods;

    }

    /**
     * 生成发货单号
     */
    public function gen_id(){
        $sign = '1'.date("Ymd");

        while(true)
        {
            list($usec, $sec) = explode(" ",microtime());
            $microtime =(float)$usec + (float)$sec;
            mt_srand($microtime);
            $randval = substr(mt_rand(), 0, -3) . rand(100, 999);

            $strList = $sign.$randval;

            $aRet =  M('b2c_delivery')->where(['delivery_id'=>$strList])->count();

            if(!$aRet){
                break;
            }
        }
        return $sign.$randval;

    }

    /**
     * @param $deli 发货数据
     * @param $delivery_id  发货单号
     */
    public  function createDelivery($deli,$delivery_id){

        $member_id =  M('b2c_orders')->where(['order_id'=>$deli['order_id'],'local_id'=>session('userInfo.local_id')])
            ->field("member_id")
            ->find();

        $corp_name =  M('b2c_dlycorp')->where(['corp_id'=>$deli['logi_id']])
            ->field("name")
            ->find();

        $delivery_bill = array(
            'delivery_id'=>$delivery_id,
            'order_id'=>$deli['order_id'],
            'member_id'=>$member_id['member_id'],
            'money'=>$deli['money'],
            'delivery'=>$deli['delivery'],
            'logi_id'=>$deli['logi_id'],
            'logi_name'=>$corp_name['name'],
            'logi_no'=>$deli['logi_no'],
            'ship_name'=>$deli['ship_name'],
            'ship_area'=>$deli['ship_area'],
            'ship_addr'=>$deli['ship_addr'],
            'ship_zip'=>$deli['ship_zip'],
            'ship_mobile'=>$deli['ship_mobile'],
            't_begin'=>time(),
            'op_name'=>session('userInfo.username'),
            'local_id'=>session('userInfo.local_id'),
            'status'=>'succ',

        );
        if(empty($deli['ship_addr'])){
            return array('msg'=>'请填写收货地址','status'=>0);
        }

        if(empty($deli['ship_mobile'])){
            return array('msg'=>'手机号码不能为空','status'=>0);
        }
        if(empty($deli['ship_name'])){
            return array('msg'=>'收货人姓名','status'=>0);
        }


       $result = M('b2c_delivery')->data($delivery_bill)->add();

        if($result){
            return array('msg'=>'发货成功','status'=>1);
        }else{
            return array('msg'=>'发货失败','status'=>0);
        }


    }

    /**
     * 发货单详情
     */
    public  function  createDeItems($deli,$delivery_id,$orderGoods){

        foreach ($orderGoods['product'] as $k=>$item){
            $deli_item[$k]['delivery_id'] = $delivery_id;
            $deli_item[$k]['order_item_id'] = $item['item_id'];
            $deli_item[$k]['item_type'] = 'goods';
            $deli_item[$k]['product_id'] = $item['product_id'];
            $deli_item[$k]['product_bn'] = $item['bn'];
            $deli_item[$k]['product_name'] = $item['name'];
            $deli_item[$k]['number'] = $deli['send'][$item['item_id']];


            $result = M('b2c_delivery_items')->data($deli_item[$k])->add();
             if(!$result){
                 return array('msg'=>'添加发货详情失败','status'=>0);
                 break;
            }
        }


    }
    /**
     *发货订单详情【货品明细】
     *
     */
    public function createOrderDeli($arrDelivery,$delivery_id,$orderGoods){


        $items = serialize($orderGoods['product']);
        $de_product = array(
            'order_id'=>$arrDelivery['order_id'],
            'dlytype'=>'delivery',
            'dly_id'=>$delivery_id,
            'items'=>$items,
        );
        $result = M('b2c_order_delivery')->data($de_product)->add();
        if(!$result){
            return array('msg'=>'添加订单详情【货品明细】','status'=>0);
        }
    }



    /**
     * 更新order_items
     */
    public function orderItems($item_id,$orderGoods){

        foreach ($item_id['send'] as $k=>$item){
            $arrItem[$k]['item_id'] = $k;
            $arrItem[$k]['sendnum'] = $item;
            $result = M('b2c_order_items')->where(['item_id'=>$k])->setInc('sendnum',$item);
        }

        $orderGoods = $this->orderDetail($item_id['order_id']);
        foreach ($orderGoods['product'] as $k=>$item){
            $sendnum += $item['sendnum'];
            $buynum += $item['nums'];
        }



        //查询订单详情，发货量< 购买量  ship_status=2   发货量 = 购买量 1  ship_status=2
        if($sendnum < $buynum){
              M('b2c_orders')->where(['order_id'=>$item_id['order_id'],'local_id'=>session('userInfo.local_id')])->save(['ship_status'=>'2']);
        }elseif ($sendnum == $buynum){
             M('b2c_orders')->where(['order_id'=>$item_id['order_id'],'local_id'=>session('userInfo.local_id')])->save(['ship_status'=>'1']);
        }


        return true;

    }



    /**
     * 库存更改
     */
    public function storeChange($order,$orderGoods){


        foreach ($orderGoods['product'] as $k=>$item){
            //更新店铺商品表
            M('webpos_store_products')->where(['product_id'=>$item['product_id'],'local_id'=>session('userInfo.local_id')])
               ->setDec('store',$order['send'][$item['item_id']]);
            M('webpos_store_products')->where(['product_id'=>$item['product_id'],'local_id'=>session('userInfo.local_id')])
                ->setDec('freez',$order['send'][$item['item_id']]);

        }
        return true;


    }

    /**
     * 导出数据为excel表格
     *@param $data    一个二维数组,结构如同从数据库查出来的数组
     *@param $title   excel的第一行标题,一个数组,如果为空则没有标题
     *@param $filename 下载的文件名
     *@examlpe
     */
    function exportexcel($data=array(),$title=array(),$filename='report'){

        header("Content-type:application/octet-stream");
        header("Accept-Ranges:bytes");
        header("Content-type:application/vnd.ms-excel");
        header("Content-Disposition:attachment;filename=".$filename.".xls");
        header("Pragma: no-cache");
        header("Expires: 0");


        //导出xls 开始
            if (!empty($title)){
                foreach ($title as $k => $v) {
                    $title[$k]=iconv("UTF-8", "gb2312",$v);
                }
                $title= implode("\t", $title);
                echo "$title\n";
            }
            if (!empty($data)){
                foreach($data as $key=>$val){
                    foreach ($val as $ck => $cv) {
                        $data[$key][$ck]=iconv("UTF-8", "gb2312", $cv);
                    }
                    $data[$key]=implode("\t", $data[$key]);

                }
                echo implode("\n",$data);
            }
            exit;


    }


}